﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using RuleCode.WebControls;
using System.IO;      

namespace ERPTemplate.Public
{
    public partial class CustomFilter : System.Web.UI.Page
    {

        DataTable sortingDataTable;
        DataTable rangeDataTable;

        protected void Page_Load(object sender, EventArgs e)
        {
            bool validateRight = false;
            validateRight = !String.IsNullOrEmpty(Request["id"]) && !String.IsNullOrEmpty(Request["tablename"])
                           && ((!String.IsNullOrEmpty (Request["queryname"])&& Request["type"]=="edit") || Request["type"]=="new");
            if (!validateRight)
            {
                Response.Clear();
                Response.Write("对不起，您没有权限访问该页面（页面参数不正确）！");
                Response.End();
                return;
            }

            if (!IsPostBack)
            {
                InitQuery();
            }
        }    

        protected void CreateNewDataTable(int type)
        {
            //创建表
            if ((type&0x01)==1)
            {
                sortingDataTable = new DataTable();
                sortingDataTable.TableName = RuleQueryTable.SortingDataTableName;
                this.sortingDataTable.Columns.Clear();
                this.sortingDataTable.Columns.Add("ID");
                this.sortingDataTable.Columns.Add("表名");
                this.sortingDataTable.Columns["表名"].AllowDBNull = false;
                this.sortingDataTable.Columns.Add("字段名");
                this.sortingDataTable.Columns["字段名"].AllowDBNull = false;
                this.sortingDataTable.Columns.Add("排序方向");
                this.sortingDataTable.Columns["排序方向"].AllowDBNull = false;
            }

            if ((type & 0x10) == 1)
            {
                rangeDataTable = new DataTable();
                rangeDataTable.TableName = RuleQueryTable.RangeDataTableName;
                this.rangeDataTable.Columns.Clear();
                this.rangeDataTable.Columns.Add("ID");
                this.rangeDataTable.Columns.Add("分组");
                this.rangeDataTable.Columns.Add("表名");
                this.rangeDataTable.Columns["表名"].AllowDBNull = false;
                this.rangeDataTable.Columns.Add("字段名");
                this.rangeDataTable.Columns["字段名"].AllowDBNull = false;
                this.rangeDataTable.Columns.Add("过滤操作");
                this.rangeDataTable.Columns["过滤操作"].AllowDBNull = false;
                this.rangeDataTable.Columns.Add("设置的值");
                this.rangeDataTable.Columns["设置的值"].AllowDBNull = false;
                this.rangeDataTable.Columns.Add("设置描述");
                this.rangeDataTable.Columns["设置描述"].AllowDBNull = false;
            }     
        }

        protected void InitQuery()
        {

            TextBox_QueryName.Text = Request["queryname"];
            OldQueryNameSpan.InnerHtml = Request["queryname"];
            CurrentQueryName.Value = Request["queryname"];

            //修改Query
            if (Request["type"] == "edit")
            {
                ModifyQueryDiv.Visible = true;
                NewQueryDiv.Visible = false;

                if (Request["queryname"] != null)
                {
                    string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
                    string queryXmlFileName = Path.Combine(queryXmlFilePath, Request["queryname"] + ".xml");
                    RuleQueryTable.CreateNewQueryXmlFile(queryXmlFileName);

                    DataSet dSet = new DataSet();
                    dSet.ReadXml(queryXmlFileName);
                    if (dSet != null && dSet.Tables.Count > 0)
                    {
                        this.sortingDataTable = dSet.Tables[RuleQueryTable.SortingDataTableName];
                        this.rangeDataTable = dSet.Tables[RuleQueryTable.RangeDataTableName];
                    }
                    if (this.sortingDataTable == null)
                        CreateNewDataTable(1);
                    if (this.rangeDataTable == null)
                        CreateNewDataTable(2);
                }
                
            }
            //新建Query
            else if (Request["type"] == "new")
            {
                ModifyQueryDiv.Visible = false;
                NewQueryDiv.Visible = true;
                CreateNewDataTable(3);
            }
            else
                return;

            
            
            DataList_Filter.DataSource = this.rangeDataTable;
            DataList_Filter.DataBind();
            DataList_Sort.DataSource = this.sortingDataTable;
            DataList_Sort.DataBind();
        }

        protected void Button_ModifyQueryName_Click(object sender, EventArgs e)
        {
            if (TextBox_QueryName.Text.Trim() != string.Empty && Request["type"]=="new")
            {
                try
                {
                    string oldQueryFileName = OldQueryNameSpan.InnerHtml;
                    string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
                    string oldQueryXmlFileName = Path.Combine(queryXmlFilePath, (oldQueryFileName + ".xml").Trim ("\\".ToCharArray ()));
                    string newQueryXmlFileName = Path.Combine(queryXmlFilePath, (TextBox_QueryName.Text + ".xml").Trim("\\".ToCharArray ()));


                    if (newQueryXmlFileName != oldQueryXmlFileName)
                    {
                        if (File.Exists(newQueryXmlFileName))
                        {
                            MessageBox.Show(this.Page, "对不起，已经存在同名的Query，请重新设置名称！");
                            return;
                        }
                        else
                        {
                            //File.Copy(oldQueryXmlFileName, newQueryXmlFileName, true);
                            //File.Delete(oldQueryXmlFileName);
                            RuleQueryTable.CreateNewQueryXmlFile(newQueryXmlFileName);
                            OldQueryNameSpan.InnerHtml = TextBox_QueryName.Text;
                            CurrentQueryName.Value = TextBox_QueryName.Text;
                            QueryNameB.InnerHtml = TextBox_QueryName.Text;
                            Button_ModifyQueryName.Visible = false;
                            TextBox_QueryName.ReadOnly = true;

                            MessageBox.ShowAndRedirect(this.Page, "新建Query成功，请修改Query!", "FilterCustomize.aspx?type=edit&tablename="+Request["tablename"]+"&id="+Request["id"]+"&queryname="+TextBox_QueryName .Text );
                        }
                    }
                }
                catch (Exception error)
                {
                }
            }
            else {
                MessageBox.Show(this.Page,"Query 的名称不能为空！");
            }
        }  
    }
}
